import time
import re
import json
import urllib
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import math
import base64
from urllib.parse import urlencode
import requests
from lxml import etree


class spider(BaseTaxPolicySpider):
    name = "jinzhou_jzsnyncj"

    province: str = "辽宁省"  # 取表格
    city: str = "锦州市"  # 取表格
    county: str = ""  # 取表格
    park: str = "None"  # 取表格
    source: str = "锦州市农业农村局"  # 取表格 同一个来源合并
    url: str = "https://nyncj.jz.gov.cn/xxgk/fdzdgknr/zcwjjd.htm"

    def start_requests(self):
        url = "https://nyncj.jz.gov.cn/xxgk/fdzdgknr/zcwjjd.htm"

        # 设置请求头
        yield scrapy.Request(url=url, callback=self.detail_requests)

    def detail_requests(self, response, **kwargs):
        links = response.xpath("//div[@class='list-box']/ul/li/a/@href").getall()  # 取链接
        date_list = response.xpath("//div[@class='list-box']/ul/li/span/text()").getall()  # 取日期
        if len(date_list) == len(links):
            for i in range(len(links)):
                if 'javascript' in links[i]:
                    continue
                if links[i].count('.') == 5:
                    links[i] = f"https://nyncj.jz.gov.cn{links[i][5:]}"
                if links[i].count('.') == 7:
                    links[i] = f"https://nyncj.jz.gov.cn{links[i][8:]}"
                print('detail_url', links[i])
                yield scrapy.Request(links[i], callback=self.parse_detail, meta={'date': date_list[i]})
        else:
            raise ValueError('error')
        # 翻页逻辑  原网页暂无翻页
        # if response.meta.get("is_next") is not False:
        #     # 正则表达式模式，匹配数字
        #     pattern = r"共(\d+)条</span>"  # 匹配形如 1/10 页 的模式，其中(\d+)用于捕获数字10
        #
        #     # 使用re.search()函数搜索匹配项
        #     total_num = int(re.search(pattern, response.text).group(1))
        #     pages = math.ceil(total_num / 20)
        #     print("总页数：", pages)
        #     for page in range(2, pages+1):
        #         print("当前页：", page)
        #         url = f"https://zjj.jz.gov.cn/xxgk/fdzdgknr/zcyjd/{page-1}.htm"
        #         print('page_url', url)
        #         yield scrapy.Request(url=url, callback=self.detail_requests, meta={'is_next': False})

    def parse_list(self, response, **kwargs):
        pass

    def parse_detail(self, response, **kwargs):
        item = Item()
        if '.pdf' in response.url or '.doc' in response.url:
            content = response.url
        else:
            content = response.xpath(".").get()
        item['title'] = response.xpath("""string(//head/title/text())""").get()
        item['source_url'] = response.url
        item['publish_date'] = response.meta.get('date')
        item['content'] = content
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        # print("item", item)
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jinzhou_jzsnyncj".split())
